import React, { useState, useEffect, useCallback } from 'react';
import { Card, Row, Col, Table, Input, Button, message, Modal, Form, Space, Select, Transfer } from 'antd';
import { PlusOutlined, EyeOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import {
    getApplicationMetrics,
    updateApplication,
    deleteApplication,
    type ApplicationData
} from '../../services/metrics';
import {
    getAllBaseApplications,
    searchBaseApplications,
    type BaseApplicationData
} from '../../services/baseApplication';
import { getBusinessUnitsForApplication, createUnit } from '../../services/unit';

const { Search } = Input;

const ApplicationView: React.FC = () => {
    const navigate = useNavigate();
    const [loading, setLoading] = useState(false);
    const [applications, setApplications] = useState<ApplicationData[]>([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const [searchText, setSearchText] = useState('');
    const [modalVisible, setModalVisible] = useState(false);
    const [editingApp, setEditingApp] = useState<ApplicationData | null>(null);
    const [form] = Form.useForm();
    const [baseApplications, setBaseApplications] = useState<BaseApplicationData[]>([]);
    const [selectedBaseApp, setSelectedBaseApp] = useState<BaseApplicationData | null>(null);
    const [searchingApps, setSearchingApps] = useState(false);
    const [availableUnits, setAvailableUnits] = useState<any[]>([]);
    const [selectedUnitKeys, setSelectedUnitKeys] = useState<string[]>([]);
    const [loadingUnits, setLoadingUnits] = useState(false);

    // 智能判断搜索类型：6位数字按应用ID搜索，否则按应用名称搜索
    const detectSearchType = (value: string): 'appId' | 'appName' => {
        // 判断是否为6位数字（可能包含前导零）
        const is6DigitNumber = /^\d{6}$/.test(value);
        return is6DigitNumber ? 'appId' : 'appName';
    };

    // 获取应用列表数据
    const fetchApplications = useCallback(async (params = {}) => {
        setLoading(true);
        try {
            const searchParams: any = {
                current: pagination.current,
                size: pagination.pageSize,
                ...params,
            };

            // 智能判断搜索类型并添加对应的搜索参数
            if (searchText) {
                const searchType = detectSearchType(searchText);
                if (searchType === 'appName') {
                    searchParams.appName = searchText;
                } else {
                    searchParams.appId = searchText;
                }
            }

            const response = await getApplicationMetrics(searchParams);

            // BaseResponse 格式: { code: 0, msg: "success", data: {...} }
            if (response.code === 0) {
                const data = response.data;
                setApplications(data.records || []);
                setPagination(prev => ({
                    ...prev,
                    current: data.current || 1,
                    total: data.total || 0,
                }));
            } else {
                message.error(response.msg || '获取应用数据失败');
            }
        } catch (error) {
            console.error('获取应用数据失败:', error);
            message.error('获取应用数据失败');
        } finally {
            setLoading(false);
        }
    }, [pagination.current, pagination.pageSize, searchText]);

    useEffect(() => {
        fetchApplications();
    }, [fetchApplications]);

    // 搜索处理
    const handleSearch = (value: string) => {
        setSearchText(value);
        setPagination(prev => ({ ...prev, current: 1 }));
        const searchParams: any = { current: 1 };
        if (value) {
            const searchType = detectSearchType(value);
            if (searchType === 'appName') {
                searchParams.appName = value;
            } else {
                searchParams.appId = value;
            }
        }
        fetchApplications(searchParams);
    };

    // 分页变化处理
    const handleTableChange = (newPagination: any) => {
        setPagination(prev => ({
            ...prev,
            current: newPagination.current,
            pageSize: newPagination.pageSize,
        }));
    };

    // 查看应用详情
    const handleViewApplication = (appId: string) => {
        navigate(`/metrics/applications/${appId}`);
    };

    // 编辑应用
    const handleEditApplication = (app: ApplicationData) => {
        setEditingApp(app);
        form.setFieldsValue(app);
        setModalVisible(true);
    };

    // 删除应用
    const handleDeleteApplication = (appId: string) => {
        Modal.confirm({
            title: '确认删除',
            content: `确定要删除应用 ${appId} 吗？此操作不可逆。`,
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                try {
                    const response = await deleteApplication(appId);
                    if (response.code === 0) {
                        message.success('删除成功');
                        fetchApplications();
                    } else {
                        message.error(response.msg || '删除失败');
                    }
                } catch (error) {
                    console.error('删除失败:', error);
                    message.error('删除失败');
                }
            },
        });
    };

    // 获取基础应用列表
    const fetchBaseApplications = async () => {
        try {
            const response = await getAllBaseApplications();
            console.log('基础应用响应:', response);
            // BaseResponse 格式: { code: 0, msg: "success", data: [...] }
            if (response.code === 0) {
                setBaseApplications(response.data || []);
            }
        } catch (error) {
            console.error('获取基础应用列表失败:', error);
        }
    };

    // 搜索基础应用
    const handleSearchBaseApps = async (keyword: string) => {
        if (!keyword.trim()) {
            fetchBaseApplications();
            return;
        }

        setSearchingApps(true);
        try {
            const response = await searchBaseApplications(keyword);
            console.log('搜索基础应用响应:', response);
            // BaseResponse 格式: { code: 0, msg: "success", data: [...] }
            if (response.code === 0) {
                setBaseApplications(response.data || []);
            }
        } catch (error) {
            console.error('搜索基础应用失败:', error);
        } finally {
            setSearchingApps(false);
        }
    };

    // 获取业务单元列表（用于添加应用）
    const fetchAvailableUnits = async (appId?: string) => {
        setLoadingUnits(true);
        try {
            const response = await getBusinessUnitsForApplication(appId);
            console.log('获取业务单元列表响应:', response);
            if (response.code === 0) {
                const businessUnits = response.data || [];
                console.log('业务单元数据:', businessUnits);

                // 转换为Transfer需要的格式，并标记已配置的单元
                const units = businessUnits.map((unit: any) => ({
                    unitId: unit.unitId,
                    unitNameCn: unit.unitNameCn,
                    teamName: unit.teamName,
                    gitlabProjectUrl: unit.gitlabProjectUrl,
                    gitlabProjectId: unit.gitlabProjectId,
                    firstUnitType: unit.firstUnitType,
                    appId: unit.appId,
                    appName: unit.appName,
                    isConfigured: unit.isConfigured || false // 是否已在unit_config中配置
                }));

                setAvailableUnits(units);

                // 自动选中已配置的单元
                const configuredUnits = units
                    .filter((unit: any) => unit.isConfigured)
                    .map((unit: any) => unit.unitId);
                setSelectedUnitKeys(configuredUnits);

            } else {
                console.error('获取业务单元列表失败:', response.msg);
                message.error(response.msg || '获取业务单元列表失败');
            }
        } catch (error) {
            console.error('获取业务单元列表失败:', error);
            message.error('获取业务单元列表失败');
        } finally {
            setLoadingUnits(false);
        }
    };

    // 选择基础应用
    const handleSelectBaseApp = (appId: string) => {
        const app = baseApplications.find(app => app.appId === appId);
        if (app) {
            setSelectedBaseApp(app);
            // 自动填充表单
            form.setFieldsValue({
                appId: app.appId,
                appName: app.appName,
                ownTeam: app.devTeam,
            });
            // 获取该应用下的业务单元
            fetchAvailableUnits(app.appId);
        }
    };

    // 提交表单
    const handleSubmit = async (values: ApplicationData) => {
        try {
            if (editingApp) {
                // 更新
                const response = await updateApplication(editingApp.appId, values);
                if (response.code === 0) {
                    message.success('更新成功');
                } else {
                    message.error(response.msg || '更新失败');
                    return;
                }
            } else {
                // 从基础应用创建 - 批量创建单元配置
                if (!selectedBaseApp) {
                    message.error('请先选择要添加的基础应用');
                    return;
                }

                if (selectedUnitKeys.length === 0) {
                    message.error('请至少选择一个单元');
                    return;
                }

                // 批量创建单元配置
                let successCount = 0;
                let skipCount = 0; // 已存在的单元数量
                let errorCount = 0;
                const errors: string[] = [];
                const skippedUnits: string[] = [];

                for (const unitId of selectedUnitKeys) {
                    try {
                        const unitDetail = availableUnits.find(unit => unit.unitId === unitId);
                        const unitConfigData = {
                            unitId: unitId,
                            appId: selectedBaseApp.appId,
                            unitType: unitDetail?.firstUnitType || 'unknown',
                            ownTeam: unitDetail?.teamName || '',
                            ownCenter: '',
                            gitRepoUrl: unitDetail?.gitlabProjectUrl || '',
                            gitRepoId: unitDetail?.gitlabProjectId || '',
                            defaultBranch: 'master',
                            currentBranch: 'master',
                            // 启用默认扫描任务
                            saTask: true,
                            gitTask: true,
                            apmTask: false,
                            jarTask: true,
                            statisticsTask: true
                        };

                        const response = await createUnit(unitConfigData);
                        if (response.code === 0) {
                            // 检查是否是因为已存在而"成功"
                            if (unitDetail?.isConfigured) {
                                skipCount++;
                                skippedUnits.push(unitId);
                            } else {
                                successCount++;
                            }
                        } else {
                            // 检查是否是重复键错误
                            if (response.msg && response.msg.includes('Duplicate entry')) {
                                skipCount++;
                                skippedUnits.push(unitId);
                            } else {
                                errorCount++;
                                errors.push(`${unitId}: ${response.msg || '创建失败'}`);
                            }
                        }
                    } catch (error: any) {
                        // 检查是否是重复键错误
                        if (error.message && error.message.includes('Duplicate entry')) {
                            skipCount++;
                            skippedUnits.push(unitId);
                        } else {
                            errorCount++;
                            errors.push(`${unitId}: ${error.message || '创建失败'}`);
                        }
                    }
                }

                // 显示结果
                const messages = [];
                if (successCount > 0) {
                    messages.push(`成功创建 ${successCount} 个单元配置`);
                }
                if (skipCount > 0) {
                    messages.push(`跳过 ${skipCount} 个已存在的单元配置`);
                }

                if (errorCount === 0) {
                    message.success(messages.join('，'));
                } else if (successCount + skipCount > 0) {
                    message.warning(`${messages.join('，')}，${errorCount} 个失败`);
                    console.error('创建失败的单元:', errors);
                } else {
                    message.error('所有单元配置创建失败');
                    console.error('创建失败的单元:', errors);
                    return;
                }
            }

            setModalVisible(false);
            setEditingApp(null);
            setSelectedBaseApp(null);
            setSelectedUnitKeys([]);
            form.resetFields();
            fetchApplications();
        } catch (error) {
            console.error('操作失败:', error);
            message.error('操作失败');
        }
    };

    // 表格列定义
    const columns = [
        {
            title: '应用ID',
            dataIndex: 'appId',
            key: 'appId',
            width: 180,
            render: (text: string, record: ApplicationData) => (
                <Button
                    type="link"
                    onClick={() => handleViewApplication(record.appId)}
                    style={{ padding: 0, fontWeight: '500' }}
                >
                    {text}
                </Button>
            ),
        },
        {
            title: '应用名称',
            dataIndex: 'appName',
            key: 'appName',
            width: 200,
        },
        {
            title: '归属团队',
            dataIndex: 'ownTeam',
            key: 'ownTeam',
            width: 180,
            render: (text: string) => text || '-',
        },
        {
            title: '单元数',
            dataIndex: 'unitCount',
            key: 'unitCount',
            width: 100,
            render: (count: number) => count || 0,
        },
        {
            title: '操作',
            key: 'action',
            width: 150,
            fixed: 'right' as const,
            render: (_: any, record: ApplicationData) => (
                <Space size="small">
                    <Button
                        type="text"
                        size="small"
                        icon={<EyeOutlined />}
                        onClick={() => handleViewApplication(record.appId)}
                        title="查看详情"
                    />
                    <Button
                        type="text"
                        size="small"
                        icon={<EditOutlined />}
                        onClick={() => handleEditApplication(record)}
                        title="编辑"
                    />
                    <Button
                        type="text"
                        size="small"
                        icon={<DeleteOutlined />}
                        onClick={() => handleDeleteApplication(record.appId)}
                        danger
                        title="删除"
                    />
                </Space>
            ),
        },
    ];

    return (
        <div style={{ padding: '24px 0' }}>
            {/* 应用汇总表格 */}
            <Card
                title="应用汇总"
                extra={
                    <Space>
                        <Search
                            placeholder="搜索应用（6位数字按ID，其他按名称）"
                            allowClear
                            value={searchText}
                            onChange={(e) => setSearchText(e.target.value)}
                            onSearch={handleSearch}
                            style={{ width: 300 }}
                        />
                        <Button
                            type="primary"
                            icon={<PlusOutlined />}
                            onClick={() => {
                                setEditingApp(null);
                                setSelectedBaseApp(null);
                                setSelectedUnitKeys([]);
                                form.resetFields();
                                fetchBaseApplications();
                                setModalVisible(true);
                            }}
                        >
                            添加应用
                        </Button>
                    </Space>
                }
            >
                <Table
                    columns={columns}
                    dataSource={applications}
                    loading={loading}
                    pagination={{
                        current: pagination.current,
                        pageSize: pagination.pageSize,
                        total: pagination.total,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total, range) =>
                            `显示第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`,
                    }}
                    onChange={handleTableChange}
                    rowKey="appId"
                    scroll={{ x: 800 }}
                />
            </Card>

            {/* 添加/编辑应用弹窗 */}
            <Modal
                title={editingApp ? '编辑应用' : '添加应用'}
                open={modalVisible}
                onCancel={() => {
                    setModalVisible(false);
                    setEditingApp(null);
                    setSelectedBaseApp(null);
                    setSelectedUnitKeys([]);
                    form.resetFields();
                }}
                footer={null}
                width={800}
            >
                <Form
                    form={form}
                    layout="vertical"
                    onFinish={handleSubmit}
                >
                    {!editingApp && (
                        <Form.Item
                            label="选择基础应用"
                            rules={[{ required: true, message: '请选择要添加的基础应用' }]}
                        >
                            <Select
                                showSearch
                                placeholder="请搜索并选择要添加的应用"
                                loading={searchingApps}
                                onSearch={handleSearchBaseApps}
                                onChange={handleSelectBaseApp}
                                value={selectedBaseApp?.appId}
                                filterOption={false}
                                style={{ width: '100%' }}
                                optionLabelProp="label"
                            >
                                {baseApplications.map(app => (
                                    <Select.Option
                                        key={app.appId}
                                        value={app.appId}
                                        label={app.appName}
                                    >
                                        <div style={{ padding: '4px 0' }}>
                                            <div style={{ fontWeight: 'bold', marginBottom: '2px' }}>
                                                {app.appName}
                                            </div>
                                            <div style={{ fontSize: '12px', color: '#666', lineHeight: '1.2' }}>
                                                ID: {app.appId}
                                            </div>
                                            {app.devTeam && (
                                                <div style={{ fontSize: '12px', color: '#999', lineHeight: '1.2' }}>
                                                    团队: {app.devTeam}
                                                </div>
                                            )}
                                        </div>
                                    </Select.Option>
                                ))}
                            </Select>
                        </Form.Item>
                    )}

                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                name="appId"
                                label="应用ID"
                                rules={[{ required: true, message: '请输入应用ID' }]}
                            >
                                <Input
                                    placeholder="请输入应用ID"
                                    disabled
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                name="appName"
                                label="应用名称"
                                rules={[{ required: true, message: '请输入应用名称' }]}
                            >
                                <Input placeholder="请输入应用名称" disabled={!editingApp} />
                            </Form.Item>
                        </Col>
                    </Row>

                    <Form.Item
                        name="ownTeam"
                        label="归属团队"
                    >
                        <Input placeholder="请输入归属团队" disabled={!editingApp} />
                    </Form.Item>

                    {!editingApp && selectedBaseApp && (
                        <Form.Item label="选择单元">
                            <div style={{ marginBottom: '8px', color: '#666', fontSize: '13px' }}>
                                选择需要归属到此应用的单元（可多选）
                            </div>
                            {loadingUnits ? (
                                <div style={{ textAlign: 'center', padding: '20px' }}>加载中...</div>
                            ) : (
                                <Transfer
                                    dataSource={availableUnits.map(unit => ({
                                        key: unit.unitId,
                                        title: unit.unitId,
                                        description: `${unit.teamName || '未知团队'} | ${unit.unitNameCn || '业务单元'}${unit.isConfigured ? ' (已配置)' : ''}`
                                    }))}
                                    targetKeys={selectedUnitKeys}
                                    onChange={(targetKeys) => setSelectedUnitKeys(targetKeys as string[])}
                                    render={item => (
                                        <div style={{ padding: '4px 0' }}>
                                            <div style={{
                                                fontWeight: 'bold',
                                                fontSize: '14px',
                                                color: '#1890ff',
                                                marginBottom: '2px'
                                            }}>
                                                {item.title}
                                            </div>
                                            <div style={{
                                                fontSize: '12px',
                                                color: '#666',
                                                lineHeight: '1.3'
                                            }}>
                                                {item.description}
                                            </div>
                                        </div>
                                    )}
                                    titles={[
                                        <span style={{ fontSize: '14px', fontWeight: '500' }}>
                                            可选单元 ({availableUnits.length - selectedUnitKeys.length})
                                        </span>,
                                        <span style={{ fontSize: '14px', fontWeight: '500' }}>
                                            已选单元 ({selectedUnitKeys.length})
                                        </span>
                                    ]}
                                    showSearch
                                    filterOption={(inputValue, option) =>
                                        option.title.toLowerCase().includes(inputValue.toLowerCase()) ||
                                        option.description.toLowerCase().includes(inputValue.toLowerCase())
                                    }
                                    style={{ width: '100%' }}
                                    listStyle={{
                                        width: 250,
                                        height: 300,
                                        border: '1px solid #d9d9d9',
                                        borderRadius: '6px'
                                    }}
                                    operationStyle={{
                                        flexDirection: 'column',
                                        padding: '8px'
                                    }}
                                    locale={{
                                        itemUnit: '个',
                                        itemsUnit: '个',
                                        searchPlaceholder: '搜索单元',
                                        notFoundContent: '无数据'
                                    }}
                                />
                            )}
                            <div style={{
                                marginTop: '12px',
                                padding: '8px 12px',
                                background: '#f6f8fa',
                                borderRadius: '4px',
                                fontSize: '12px',
                                color: '#666'
                            }}>
                                <span style={{ fontWeight: '500' }}>选择统计：</span>
                                已选择 <span style={{ color: '#1890ff', fontWeight: 'bold' }}>{selectedUnitKeys.length}</span> 个单元，
                                剩余 <span style={{ color: '#52c41a', fontWeight: 'bold' }}>{availableUnits.length - selectedUnitKeys.length}</span> 个可选
                            </div>
                        </Form.Item>
                    )}

                    <Form.Item style={{ textAlign: 'right', marginTop: '32px', marginBottom: '8px' }}>
                        <Space size="large">
                            <Button
                                size="large"
                                onClick={() => {
                                    setModalVisible(false);
                                    setEditingApp(null);
                                    setSelectedBaseApp(null);
                                    setSelectedUnitKeys([]);
                                    form.resetFields();
                                }}
                                style={{ minWidth: '80px' }}
                            >
                                取消
                            </Button>
                            <Button
                                type="primary"
                                size="large"
                                htmlType="submit"
                                disabled={!editingApp && (!selectedBaseApp || selectedUnitKeys.length === 0)}
                                style={{
                                    minWidth: '120px',
                                    fontWeight: '500'
                                }}
                            >
                                {editingApp ? '保存更新' : (
                                    selectedUnitKeys.length > 0
                                        ? `创建单元配置 (${selectedUnitKeys.length}个单元)`
                                        : '创建单元配置'
                                )}
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default ApplicationView;